package com.thread.threadfirst;

import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.http.client.OkHttp3ClientHttpRequestFactory;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;


@EnableAsync  //开启异步 此注解不仅在启动类上写 还可以在配置类上写
@SpringBootApplication
public class ThreadFirstApplication {

    public static void main(String[] args) {
        SpringApplication.run(ThreadFirstApplication.class, args);
    }

//    @Bean
//    public Redisson redisson(){
//        Config config=new Config();
//        config.useSingleServer().setAddress("redis://127.0.0.1:6379").setDatabase(0);
//        return (Redisson)Redisson.create(config);
//    }

    /**
     * 自定义线程池
     *
     * @return
     */
    //自定义线程池可以在启动类中、新建一个类、实现了AsyncConfigurer Interface接口的实现类中进行配置。
    @Bean  //这个注解是重点 不然程序会检测不到此线程池。
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(1);
        //配置最大线程数
        executor.setMaxPoolSize(1);
        //配置队列大小
        executor.setQueueCapacity(1);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("Anno-Executor");
        // rejection-policy：当pool已经达到max size、queue也满了的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是有调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();
        return executor;
    }

    /**
     * 默认：URLConnection
     * @return
     */
//    @Bean
//    public RestTemplate restTemplate(){
//        return new RestTemplate();
//    }

    /**
     * URLConnection
     * @return
     */
//    @Bean
//    public RestTemplate restTemplate(){
//        return new RestTemplate(new SimpleClientHttpRequestFactory());
//    }

    /**
     * httpClient
     * @return
     */
    @Bean("httpClient")
    public RestTemplate restTemplate(){
        return new RestTemplate(new HttpComponentsClientHttpRequestFactory());
    }

    /**
     * OKHttp3
     * @return
     */
//    @Bean
//    public RestTemplate restTemplate(){
//        return new RestTemplate(new OkHttp3ClientHttpRequestFactory());
//    }

}
